package com.randb.easyhttp.callback;

import android.app.Dialog;
import android.content.DialogInterface;

import com.randb.easyhttp.exception.ApiException;
import com.randb.easyhttp.subscriber.IProgressCancelListener;
import com.randb.easyhttp.subscriber.IProgressDialog;

import io.reactivex.disposables.Disposable;

/**
 * User: RandBII
 * Date: 2020/5/11
 * Description:
 */
public class ProgressDialogCallback<T> extends Callback<T> implements IProgressCancelListener {
    private IProgressDialog iProgressDialog;
    private Dialog mDialog;
    private boolean isShowProgress = true;
    private Disposable disposable;

    public ProgressDialogCallback(IProgressDialog dialog) {
        this.iProgressDialog = dialog;
        init(false);
    }

    private void init(boolean cancel) {
        if (iProgressDialog == null) return;
        mDialog = iProgressDialog.getDialog();
        if (mDialog == null) return;
        mDialog.setCancelable(cancel);
        if (cancel) {
            mDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    ProgressDialogCallback.this.onCancelProgress();
                }
            });
        }
    }


    @Override
    public void onStart() {
        showProgress();
    }

    private void showProgress() {
        if (!isShowProgress) {
            return;
        }
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
    }

    @Override
    public void onFinish() {
        dismissProgress();
    }

    @Override
    public void onSuccess(T t) {
        dismissProgress();
    }

    private void dismissProgress() {
        if (!isShowProgress) {
            return;
        }
        if (mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    public void onError(ApiException e) {
        dismissProgress();
    }


    @Override
    public void onCancelProgress() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    public void subscription(Disposable disposable) {
        this.disposable = disposable;
    }
}
